using System;
using System.Text;
using Exceptions;

namespace FrameIdentityReq.Frames
{
    public class StringField : BitsField, IStringField
    {
        static Encoding DefaultEncoding = Encoding.ASCII;

        byte[] Bytes;

        public StringField(IBytesBuffer buffer, int index, int count, string name)
            : base(buffer, index, count, name)
        {
            Bytes = new byte[Count >> 3];
        }

        public StringField(IField field, int count, string name)
            : this(field, field.Index + field.Count, count, name) { }

        public new string Value
        {
            get
            {
                int eof = Array.IndexOf(base.Value, (byte)0, 0);
                int count = (eof != -1) ? eof : base.Value.Length;
                return DefaultEncoding.GetString(base.Value, 0, count);
            }

            set
            {
                try
                {
                    int count = DefaultEncoding.GetBytes(value, 0, value.Length, Bytes, 0);
                    if (count < Bytes.Length) Array.Clear(Bytes, count, Bytes.Length - count);
                }
                catch (ArgumentException)
                {
                    throw new ExceptionOverLength($"{Name} 长度超出范围 {Count >> 3}");
                }
                base.Value = Bytes;
            }
        }

    }
}